package com.hqyj.bigdata.hiveproject.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hqyj.bigdata.hiveproject.entity.Users;
import com.hqyj.bigdata.hiveproject.mapper.UsersMapper;
import com.hqyj.bigdata.hiveproject.service.UsersService;
import com.hqyj.bigdata.hiveproject.util.MyUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.transaction.Transactional;

@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService {

    @Transactional(rollbackOn = Exception.class)
    @Override
    public boolean reg(Users u) throws Exception {
        try{
            //密码不能裸奔，必须加密处理。
            u.setPassword(MyUtils.encodePassword(u.getPassword()));
            //随机分配一个全宇宙不重复的用户名。
            u.setUsername(IdUtil.simpleUUID());
            //默认性别是男
            u.setGender("男");
            //默认你的出生日期是1990-01-01
            u.setBirthday("1990-01-01");

            return super.save(u);
        }catch (Exception ex){
            ex.printStackTrace();
            // 事务的回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }

    }

    @Override
    public Users login(String identify, String password) {

        QueryWrapper<Users> queryWrapper = new QueryWrapper<Users>();
        if(MyUtils.isMobileNumber(identify)){
            queryWrapper.eq("mobile",identify);
        }else if(MyUtils.isEmail(identify)){
            queryWrapper.eq("email",identify);
        }else{
            queryWrapper.eq("username",identify);
        }

        Users loginSuccessUser = super.getOne(queryWrapper);
        if(loginSuccessUser!=null){
            if(DigestUtil.bcryptCheck(password,loginSuccessUser.getPassword())){
                return loginSuccessUser;
            }else{
                return null;
            }
        }else{
            return null;
        }

        //return null;
    }

    @Override
    public boolean checkIdentifyIsReg(String identify) {
        return false;
    }
}
